package xquery;

import java.util.ArrayList;

import org.w3c.dom.Node;

public class XQueryForExp extends XQuery {
	XQVarExpPair[] forclause;
	XQVarExpPair[] letclause;
	XQExpression whereclause;
	XQExpression returnclause;
	
	//TODO: implement LET
	
	@Override
	public XPathData eval(XQContext context, ArrayList<Node> currentNodeList) {
		context.openContext();
		
		ArrayList<Node> result = new ArrayList<Node>();
		evalFor(0,context,currentNodeList,result);
		
		context.closeContext();
		
		return new XPathData(result);
	}
	
	void evalFor(int i, XQContext context, ArrayList<Node> currentNodeList, ArrayList<Node> result) {
		String var;
		XQExpression exp;
		if(i==forclause.length) {
			if(letclause != null)
			{
				context.openContext();
				XPathData expResult;
				for(int j = 0;j < letclause.length;j++)
				{
					var = letclause[j].var;
					exp = letclause[j].exp;
					expResult = exp.eval(context, currentNodeList);
					context.put(var, expResult);
				}
			}
			if(whereclause==null || whereclause.eval(context, currentNodeList).getBool())
				result.addAll(returnclause.eval(context, currentNodeList).getList());

			return;
		}	
		var = forclause[i].var;
		exp = forclause[i].exp;
		ArrayList<Node> expResult = exp.eval(context, currentNodeList).getList();
		for (Node n : expResult) {
			ArrayList<Node> list = new ArrayList<Node>();
			list.add(n);
			context.put(var, new XPathData(list));
			evalFor(i + 1, context, currentNodeList, result);
		}
	}
	public String toString()
	{
		StringBuffer sb = new StringBuffer("");
		sb.append("for ");
		for(XQVarExpPair pair : forclause)
		{
			sb.append(pair.var);
			sb.append(" in ");
			sb.append(pair.exp);
			sb.append('\n');
		}
		if(whereclause != null)
		{
			sb.append("where ");
			sb.append(whereclause);
			sb.append('\n');
		}
		sb.append("return ");
		sb.append(returnclause);
		return sb.toString();
	}
}
